package io.iec.edp.caf.multicontext.support;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class ServiceUnitManager {

    public static void getServiceUnitInfo(Map<String,String> sus, File fileInfo) {
        if (fileInfo != null && fileInfo.exists() && fileInfo.isDirectory()) {
            File[] files = fileInfo.listFiles((dir, name) -> dir.isDirectory() && name != null && name.equalsIgnoreCase("ServiceUnit.json"));

            //识别为su目录
            if (files != null && files.length > 0) {
                File file = files[0];
                //读取serviceunit.json内容,获取准确的su名称
                String suName = readServiceUnitName(readToBuffer(file.getAbsolutePath()));
                if (suName != null) {
                    if(!sus.containsKey(file.getName())){
                        sus.put(suName,file.getParentFile().getAbsolutePath());
                    }
                }

            }else {
                //非su目录，继续递归，仅查找目录
                files = fileInfo.listFiles(pathname -> !pathname.isFile());
                if (files != null)
                    for (File file : files) {
                        getServiceUnitInfo(sus, file);
                    }
            }
        }
    }
    /**
     * 将JSON字符串转换为对象
     *
     * @param content
     * @return
     */
    private static String readServiceUnitName(String content) {
        if (content == null || "".equals(content))
            return null;

        content = content.substring(content.indexOf(":") + 1, content.lastIndexOf("}"));
        Map<String,Object> info = deserialize(content, Map.class);
        if (info == null)
            return null;
        if(info.containsKey("ServiceUnitName")) return info.get("ServiceUnitName").toString();
        return null;
    }

    /**
     * 读取文本文件内容
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    private static String readToBuffer(String filePath) {
        StringBuffer buffer = new StringBuffer();
        try {
            InputStream stream = null;
            BufferedReader reader = null;
            try {
                File file = new File(filePath);
                if (!file.exists())
                    return null;
                stream = new FileInputStream(file);
                String line; // 用来保存每行读取的内容
                reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
                line = reader.readLine(); // 读取第一行
                while (line != null) { // 如果 line 为空说明读完了
                    buffer.append(line); // 将读到的内容添加到 buffer 中
                    buffer.append("\n"); // 添加换行符
                    line = reader.readLine(); // 读取下一行
                }
            } finally {
                if (reader != null)
                    reader.close();
                if (stream != null)
                    stream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static <T> T deserialize(String str, Class<T> clazz) {
        //反序列化时空串【""】会报错，正常的空串应该【""""】
        if((str == null) || (str.length() == 0) || clazz == null){
            return null;
        }
        try {
            //return clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz);
            return new ObjectMapper().readValue(str, clazz);
        } catch (Exception e) {
            System.out.println(String.format("Parse Object to String error : %s", e.getMessage()));
            return null;
        }
    }
}
